package com.codefish.codefishseckill.security;

import com.codefish.codefishseckill.utils.ResponseUtil;
import com.codefish.codefishseckill.vo.RespBeanFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/30 下午 05:24
 */
@Component
@Slf4j
public class MyAuthFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String failMessage;
        if (exception instanceof BadCredentialsException) {
            failMessage = "用户名或密码错误";
        } else {
            failMessage = exception.getMessage();
        }

        ResponseUtil.out(response, RespBeanFactory.fail(failMessage));
    }
}
